package common

import (
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/env"
	"github.com/spf13/viper"
	"os"
	"time"
)

type Config struct {
	Language struct {
		Local string `yaml:"local"`
	} `yaml:"language"`

	MySQL struct {
		MaxOpenConn     int           `yaml:"maxOpenConn"`
		MaxIdleConn     int           `yaml:"maxIdleConn"`
		ConnMaxLifeTime time.Duration `yaml:"connMaxLifeTime"`
		Addr            string        `yaml:"addr"`
		User            string        `yaml:"user"`
		Pass            string        `yaml:"pass"`
		Name            string        `yaml:"name"`
		Charset         string        `yaml:"charset"`
		Loc             string        `yaml:"loc"`
	} `yaml:"mysql"`

	Redis struct {
		Addr         string `yaml:"addr"`
		Pass         string `yaml:"pass"`
		Db           int    `yaml:"db"`
		MaxRetries   int    `yaml:"maxRetries"`
		PoolSize     int    `yaml:"poolSize"`
		MinIdleConns int    `yaml:"minIdleConns"`
	} `yaml:"redis"`

	HashIds struct {
		Secret string `yaml:"secret"`
		Length int    `yaml:"length"`
	} `yaml:"hashids"`

	Mail struct {
		Host string `yaml:"host"`
		Pass string `yaml:"pass"`
		Port string `yaml:"port"`
		To   string `yaml:"to"`
		User string `yaml:"user"`
	} `yaml:"mail"`
}

var config = new(Config)

func InitConfig() {
	workDir, err := os.Getwd()
	if err != nil {
		return
	}
	// 获取用户配置的环境，默认是 dev 开发环境
	env := env.Init().Value()
	//fmt.Println("env", env)

	viper.SetConfigName("application." + env)
	viper.SetConfigType("yaml")
	viper.AddConfigPath(workDir + "/config")
	err = viper.ReadInConfig()
	if err != nil {
		panic(err)
	}

	if err := viper.Unmarshal(config); err != nil {
		panic(err)
	}
}

func Get() Config {
	//fmt.Printf("配置数据：%#v \n", config)/**/
	return *config
}
